package cn.openea.perpartner.meily.util;

import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.core.utils.spring.SpringUtils;
import cn.openea.perpartner.meily.web.service.IRoleService;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-12-02 11:24
 */
@Slf4j
public class UserContext {
    private static final ThreadLocal<ThreadContext> contextHolder = new ThreadLocal<>();

    public static ThreadContext getContext() {
        // 初始化线程对像
        ThreadContext threadContext = contextHolder.get();
        if (threadContext == null) {
            threadContext = new ThreadContext();
            contextHolder.set(threadContext);
        }
        return threadContext;
    }

    public static void setLoginUser(LoginBody loginBody) {
        getContext().setLoginUser(loginBody);
    }
    public static void setAdmin(String flag) {
        getContext().setAdmin(flag);
    }
    public static void clear() {
        contextHolder.remove();
    }

    public static LoginBody getLoginUser() {

        return getContext().getLoginUser();
    }

    public static String getUserId() {

        return getContext().getUserId();
    }

    public static String getUserName() {

        return getContext().getUserName();
    }

    public static boolean isAdmin() {
        if (StrUtil.isBlank(getContext().isAdmin())){
            IRoleService roleService = SpringUtils.getBean(IRoleService.class);
            return roleService.checkAdmin(getUserId());
        }
        return "1".equals(getContext().isAdmin());
    }

}
